// 
//  Copyright (C) 2009 Jacek Trubłajewicz
// 
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation; either version 2 of the License, or
//  (at your option) any later version.
// 
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//  GNU General Public License for more details.
//  
//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// 

using System;
using System.Collections.Generic;

namespace wxGadu
{
	
	/// <summary>
	/// Implementation of <c>Dictionary<TKey, TValue></c>
	/// with limited constant capacity.
	/// </summary>
	/// <remarks>
	/// Adding new item to full dictionary will cause 
	/// removal of the oldest item.
	/// </remarks>
	public class LimitedDictionary<TKey, TValue> : Dictionary<TKey, TValue> 
	{
		private LimitedList<TKey> elementsList;
		private int capacity;
			
		/// <summary>
		/// Ctor
		/// </summary>
		/// <param name="capacity">
		/// A <see cref="System.Int32"/>
		/// Capacity of the dictionary
		/// </param>
		/// <exception cref="ArgumentOutOfRangeException">
		/// <c>capacity</c> value is less than 1
		/// </exception>
		public LimitedDictionary(int capacity)
		{
			if (capacity < 1)
				throw new ArgumentOutOfRangeException("Capacity value must be at least 1");
			
			this.capacity = capacity;
			elementsList = new LimitedList<TKey>(capacity);
		}
		
		public new void Add(TKey key, TValue item)
		{
			if (this.Count < capacity)
			{
				base.Add(key, item);
				elementsList.Add(key);
			}
			else
			{
				// remove the oldest item in dictionary
				base.Remove(elementsList[capacity - 1]);
				elementsList.RemoveAt(capacity - 1);
				
				// add new item
				base.Add(key, item);
				elementsList.Add(key);
			}
		}
		
		public new bool Remove(TKey key)
		{
			if (base.Remove(key))
			{
				elementsList.Remove(key);
				return true;
			}
			else
			{
				return false;
			}
		}
		
		
	}
}
